﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Workflow;
using System.Text;
using Runda.CMS.Common.Exchange;

namespace Runda.CMS.Portal.Workspace
{
    public partial class ContractComment : WorkflowPage
    {

        public Guid ContractID
        {
            get
            {
                if (txtContractID.Value == "") return Guid.Empty;
                else return new Guid(txtContractID.Value);
            }
            set
            {
                txtContractID.Value = value.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Type";
                parm.ColumnType = DbType.Int32;
                parm.ParameterName = "@Type";
                parm.ParameterValue = System.Convert.ToInt32(ContractEnumerator.ContractParms.contractAttr);
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                listContractAttribute.DataSource = new SysDictionaryBll().GetAll<SysDictionaryEntity>(parms);
                listContractAttribute.DataTextField = "Code";
                listContractAttribute.DataValueField = "ID";
                listContractAttribute.DataBind();

                if (Request.QueryString["BussinessID"] != null)
                {
                    ContractID = new Guid(Request.QueryString["BussinessID"].ToString());
                    InitForm();
                }
            }
        }

        private void InitForm()
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();

            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
                if (entity != null)
                {
                    txtContractCode.Text = entity.ContractCode;
                    listContractAttribute.SelectedValue = entity.ContractAttribute.ToString();
                    if (entity.ContractApplyDate != DateTime.MinValue)
                        txtContractApplyDate.Text = entity.ContractApplyDate.ToShortDateString();
                    //if (entity.ContractEstimateSignDate != DateTime.MinValue)
                    //    txtContractEstimateSignDate.Text = entity.ContractEstimateSignDate.ToShortDateString();
                    listContractType.Text = entity.ContractType;
                    txtContractStatement.Text = entity.ContractStatement;
                    //txtContractPeriod.Text = entity.ContractPeriod.ToString();
                    //txtGivenMaterialdesc.Text = entity.GivenMaterialdesc;
                    //txtGivenMaterialCost.Text = entity.GivenMaterialCost.ToString();
                    //txtCapitalCost.Text = entity.CapitalCost.ToString();
                    radtxtReachTo.Value = (double)entity.ReachTo;
                    radtxtRebate.Value = (double)entity.Rebate;
                    if (entity.InstanceID != Guid.Empty)
                    {
                        BindWorkflow(entity.InstanceID);
                    }
                }
            }

            if (Request.QueryString["CommentID"] != null)
            {
                WflCommentBll Commentbll = new WflCommentBll();
                WflCommentEntity ComentEnt = Commentbll.Get<WflCommentEntity>(new Guid(Request.QueryString["CommentID"]));
                if (ComentEnt != null)
                {
                    txtComment.Text = ComentEnt.Comments;
                }
                else
                {
                    lnkbtnApprove.Enabled = false;                
                }
            }
            else
                lnkbtnApprove.Visible = false;
        }

        protected void lnkbtnApprove_Click(object sender, EventArgs e)
        {
            IWorkflowInstance instance = this.GetInstance(new Guid(Request.QueryString["TrackID"]), new Guid(Request.QueryString["TaskID"]));

            instance.Comment(new Guid(Request.QueryString["CommentID"]),txtComment.Text);
            //instance.OnNextRouting += new EventHandler<RoutingEventArgs>(instance_OnNextRouting);
            //instance.Approve(txtComment.Text);

            //CtrtContractBll bll = new CtrtContractBll();
            //CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            //entity.Status = (int)Enumerator.ContractStatus.Submit;
            //bll.Update(entity);
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        void instance_OnNextRouting(object sender, RoutingEventArgs e)
        {
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            StringBuilder sb = new StringBuilder();
            if (e.RoutingEntity.NextActivityID != Guid.Empty)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = null;
                parm = new SqlDbParameter();
                parm.ColumnName = "ActivityID";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@ActivityID";
                parm.ParameterValue = e.RoutingEntity.NextActivityID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Like;
                parms.Add(parm);

                WflActivityCheckersBll wacbll = new WflActivityCheckersBll();
                List<WflActivityCheckersEntity> list = wacbll.GetAll<WflActivityCheckersEntity>(parms);

                foreach (WflActivityCheckersEntity c in list)
                {
                    sb.Append(c.UserName).Append("(").Append(c.Account).Append(")").Append(",");
                    SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(c.UserID);
                    //发送邮件给审核人
                    MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "一份合同需要您的审核，合同编号：" + txtContractCode.Text.ToString() + "");
                }
                entity.NextCheckers = sb.ToString().TrimEnd(',');
            }
            else
            {
                entity.Status = (int)Enumerator.ContractStatus.Pass;
                entity.NextCheckers = string.Empty;
            }
            bll.Update(entity);
        }

        protected void lnkbtnReject_Click(object sender, EventArgs e)
        {
            //检查当前Track是否已审过
            WflInstanceRoutingBll InstanceRoutingBll = new WflInstanceRoutingBll();
            WflInstanceRoutingEntity TrackEntity = InstanceRoutingBll.Get<WflInstanceRoutingEntity>(new Guid(Request.QueryString["TrackID"]));
            if (TrackEntity != null)
            {
                if (TrackEntity.CheckStatus > 1)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('该任务已审批过,不能重复审批!');window.close();", true);
                    return;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "alert('参数有误');window.close();", true);
                return;
            }

            IWorkflowInstance instance = this.GetInstance(new Guid(Request.QueryString["TrackID"]), new Guid(Request.QueryString["TaskID"]));
            instance.Reject(txtComment.Text);

            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            entity.NextCheckers = string.Empty;
            entity.Status = (int)Enumerator.ContractStatus.Back;
            bll.Update(entity);

            SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(entity.CreatedBy);
            MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "您提交的同被打回，合同编号：" + txtContractCode.ToString() + "");
            ClientScript.RegisterStartupScript(this.GetType(), "reject", "window.close();", true);
        }

        private void BindWorkflow(Guid InstanceID)
        {
            List<WflInstanceRoutingEntity> list = new WflInstanceRoutingBll().GetAll<WflInstanceRoutingEntity>(" and InstanceID = '" + InstanceID + "' and CheckStatus != 1 order by CheckDate");

            RepeaterApprove.DataSource = list;
            RepeaterApprove.DataBind();
        }

        public string GetStatusText(int status)
        {
            string text = string.Empty;
            EnumeratorHelper[] cs = EnumeratorHelper.GetFieldTexts(typeof(Runda.CMS.Workflow.ActivityStatus));
            foreach (EnumeratorHelper c in cs)
            {
                if (c.EnumValue == status)
                {
                    text = c.EnumDisplayText; break;
                }
            }

            return text;
        }
    }
}
